package com.jnshu.tools;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;


/**
 * @ClassName AliyunUtil
 * @Descrintion
 * @Author bd
 * @Date 2019/8/6 11:24
 * @Version 1.0
 **/
public class AliyunUtilImage {


    public String upLoad(MultipartFile file, String fileName) {


        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5d3MqgDWxHmX";
        String accessKeySecret = "Il7UEruBHnvCUr7nO4HEqVaEupeSHE";
        String bucketName = "baidongn";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 获取上传文件流。
            InputStream inputStream = file.getInputStream();

            PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, inputStream);
            // 设置URL过期时间为10年  3600l* 1000*24*365*10

            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            //获取图片上传链接
            String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();
            // 关闭client
            // 关闭OSSClient。
            ossClient.shutdown();

            return url;

        } catch (Exception e) {
            return "上传失败"+e.toString();


        }
    }

}
